package br.com.management.mentor.model.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import br.com.management.mentor.model.entities.auth.User;
import br.com.management.mentor.model.entities.view.Menu;
import br.com.management.mentor.model.entities.view.QMenu;

import com.mysema.query.jpa.impl.JPAQuery;

@Component
@Repository
public class MenusRepository {

	private QMenu qMenu = QMenu.menu;

	@Autowired
	private EntityManagerFactory emf;

	public Menu getByKey( String key ) {
		EntityManager em = emf.createEntityManager();
		JPAQuery query = new JPAQuery( em );

		try {
			return query.from( qMenu ).where( qMenu.key.eq( key ) ).uniqueResult( qMenu );
		} finally {
			if ( em != null ) em.close();
		}
	}

	public List<Menu> getPublics() {
		EntityManager em = emf.createEntityManager();
		JPAQuery query = new JPAQuery( em );

		try {
			return query.from( qMenu ).where( qMenu.permission.isNull() ).list( qMenu );
		} finally {
			if ( em != null ) em.close();
		}
	}

	public List<Menu> getByUser( User user ) {
		EntityManager em = emf.createEntityManager();
		JPAQuery query = new JPAQuery( em );
		
		try {
			if( user.isAdmin() ) return query.from( qMenu ).list( qMenu );
			return query.from( qMenu ).where( qMenu.permission.in( user.getPermissions() ) ).list( qMenu );
		} finally {
			if ( em != null ) em.close();
		}
	}

}